//
//  DWServerResponePlugin.swift
//  DWSwift
//
//  Created by GDL on 2025/6/23.
//

import Moya
import Foundation
import DWCoreLib
import Toastify
import Alamofire

public struct DWServerResponePlugin: PluginType {
    
    public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        DWGlobalLoadingState.shared.startLoading()
        return request
    }
    
    public func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        DWGlobalLoadingState.shared.stopLoading()
        handleResult(result: result, target: target)
    }
    
    private func handleResult(result: Result<Response, MoyaError>, target: TargetType){
        switch result {
        case .success(let response):
            if(response.statusCode == 200){
                // 业务错误toast
                // 示例 JSON: {"code":400, "data":null, "msg":"请求参数缺失:shop_id"}
                guard let error:DWNetworkError =  DWNetworkError.pareBusinessError(from: response.data) else{
                    return
                }
                showToast(msg: error.description, target: target)
//                ToastManager.shared.showToast(message: error.description,duration: 3.0)
//                DWRouterManager.shared.router?.showAlert(.alert, title: "默认的试试", alert: {
                    
              //  })
            }else{
                // 需要根据服务构造----解析数据
            }
        case .failure(let error):
            // MoyaError
            let netError = DWNetworkError.mapMoyaError(error)
            showToast(msg: netError.description, target: target)
            // 若为 HTTP 错误，尝试解析业务逻辑
//            ToastManager.shared.showToast(message: netError.description,duration: 3.0)
        }
    }
    
    private func showToast(msg:String, target: TargetType){
        DispatchQueue.main.async {
            ToastManager.shared.showToast(message: msg,duration: 3.0)
        }
    }
}
